#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>

int main() {
    // 创建套接字
    int serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket == -1) {
        std::cerr << "Failed to create socket." << std::endl;
        return 1;
    }

    // 设置服务器地址信息
    sockaddr_in serverAddress{};
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_addr.s_addr = INADDR_ANY;  // 接受所有网络接口上的连接
    serverAddress.sin_port = htons(9999);  // 服务器监听的端口

    // 绑定套接字到地址和端口
    if (bind(serverSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) < 0) {
        std::cerr << "Bind failed." << std::endl;
        return 1;
    }

    // 开始监听连接
    if (listen(serverSocket, 5) < 0) {  // 允许最多5个待处理的连接请求
        std::cerr << "Listen failed." << std::endl;
        return 1;
    }

    std::cout << "Server listening on port 9999..." << std::endl;

    // 接受客户端连接
    sockaddr_in clientAddress{};
    socklen_t clientAddrLength = sizeof(clientAddress);
    int clientSocket = accept(serverSocket, reinterpret_cast<sockaddr*>(&clientAddress), &clientAddrLength);
    if (clientSocket < 0) {
        std::cerr << "Accept failed." << std::endl;
        return 1;
    }

    std::cout << "Client connected." << std::endl;

    // 接收客户端消息
    char buffer[1024] = {0};
    if (recv(clientSocket, buffer, sizeof(buffer), 0) < 0) {
        std::cerr << "Receive failed." << std::endl;
        return 1;
    }
    std::cout << "Message from client: " << buffer << std::endl;

    // 发送响应给客户端
    const char* response = "Hello from server!";
    if (send(clientSocket, response, strlen(response), 0) < 0) {
        std::cerr << "Send failed." << std::endl;
        return 1;
    }
    std::cout << "Response sent to client." << std::endl;

    // 关闭套接字
    close(clientSocket);
    close(serverSocket);

    return 0;
}
